/**
 * Copyright 2010 Jake Jackson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jake.nb.ext.ant.hints.impl.dependserrors;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.jake.nb.ext.ant.hints.AntHint;
import org.jake.nb.ext.ant.hints.Configuration;
import org.jake.nb.ext.ant.hints.Paths;
import org.jake.nb.ext.ant.hints.SpanContainer;
import org.jake.nb.ext.ant.parser.Span;
import org.jake.nb.ext.ant.parser.Spans;
import org.jake.nb.ext.ant.parser.TargetSpan;
import org.netbeans.modules.editor.NbEditorUtilities;
import org.netbeans.spi.editor.hints.ErrorDescription;
import org.netbeans.spi.editor.hints.ErrorDescriptionFactory;
import org.netbeans.spi.editor.hints.Fix;
import org.netbeans.spi.editor.hints.Severity;
import org.openide.text.Line;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;

/**
 *
 * @author JakeJ
 */
@ServiceProvider(service = AntHint.class, path = "org-jake-nb-ext-ant-hints")
public class SelfReferenceInDepends implements AntHint {

  private Configuration configuration;

  public SelfReferenceInDepends() {
    configuration = new Configuration(SelfReferenceInDepends.class.getCanonicalName(),
            "Selfreference in depends",
            "Checks a depends clause does not contain a direct reference to the target the depends is defined in.",
            true,
            Severity.WARNING, Paths.DEPENDS);
  }

  @Override
  public Collection<ErrorDescription> getErrors(final SpanContainer spanContainer) {
    final Collection<ErrorDescription> errors = new HashSet<ErrorDescription>();
    final Spans dependSpans = spanContainer.getDependSpans();
    for (final Span span : dependSpans.getSpans()) {
      final String fullAttribute = getDepends(span);
      if (fullAttribute.length() > 0) {
        final int firstQuote = fullAttribute.indexOf('"') + 1; // NOI18N
        final int lastQuote = fullAttribute.indexOf('"', firstQuote); // NOI18N
        final String dependsClause = fullAttribute.substring(firstQuote, lastQuote);
        errors.addAll(checkClause(dependsClause, span, spanContainer));
      }
    }

    return errors;
  }

  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  private Collection<ErrorDescription> checkClause(final String clause, final Span span, final SpanContainer container) {
    final Collection<ErrorDescription> retVal = new HashSet<ErrorDescription>();
    // get the target this depends it defined in
    final TargetSpan targetSpan = (TargetSpan) container.getTargetSpans().getSpan(span.getStart() + 1);
    if (targetSpan != null && targetSpan.getName().length() > 0) {
      final StringTokenizer tokenizer = new StringTokenizer(clause, ","); // NOI18N
      boolean single = tokenizer.countTokens() == 1;
      final List<String> toRemove = new ArrayList<String>();
      while (tokenizer.hasMoreTokens()) {
        final String trimmedToken = tokenizer.nextToken().trim();
        if(targetSpan.getName().trim().equals(trimmedToken)) {
          toRemove.add(trimmedToken);
        }
      }
      
      if(!toRemove.isEmpty()) {
        retVal.add(createError(span, toRemove, single));
      }
    }

    return retVal;
  }

  /**
   * Gets the full string of the depends attribute, e.g. depends="a, b", but only in case there are multiple entries
   * @param span
   * @return
   */
  private String getDepends(final Span span) {
    String text = null;
    try {
      text = span.getDocument().getText(span.getStart(), span.getLength() + 1);
    } catch (BadLocationException ex) {
      text = ""; // NOI18N
    }

    return text;
  }

  private ErrorDescription createError(final Span span, final List<String> toRemove, boolean createRemoveDepends) {
    final Document document = span.getDocument();

    final List<Fix> fixes = new ArrayList<Fix>();
    fixes.add(new RemoveInvalidEntriesForDependsFix(document, span, toRemove, NbBundle.getMessage(this.getClass(), "FIX_REMOVE_SELF_REFERENCE")));  // NOI18N
    if(createRemoveDepends) {
      fixes.add(new RemoveDependsFix(document, span));
    }

    final Line line = NbEditorUtilities.getLine(document, span.getStart(), true);
    final ErrorDescription desc = ErrorDescriptionFactory.createErrorDescription(configuration.getSeverity(),
            NbBundle.getMessage(this.getClass(), "DESC_ERR_REMOVE_SELF_REFERENCE"), fixes, document, // NOI18N
            line.getLineNumber() + 1);
    return desc;
  }
}
